﻿using library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Reflection;
using windows_desktop.Properties;
using Microsoft.Build;
using Microsoft.Build.Execution;
using System.Diagnostics;

namespace windows_desktop
{
    static class Program
    {


        internal static int WebPort;

        internal static int p2pPort;

        internal static byte[] p2pAddress;

        internal static int Timeout = 60000;

        internal static int MaxNonRangeDownloadSize = 1024 * 50;

        internal static UIHelper UIHelper;

        internal static string AppName = "la-red";

        internal static string webCache = "cache";

        internal static string webHome = "k5c0241K9ckEw3ruLh2ZTUppkFtTurVikZJTuMn8UX8=";

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            #if RELEASE || BOOTSTRAP

                        if(Install())
                            return;

                #if BOOTSTRAP

                        Client.BootStrap();

                #endif

            #endif

            //string msbuildFileName = @"C:\arede - Copy\windows-desktop\windows-desktop.csproj";

            //BuildManager manager = BuildManager.DefaultBuildManager;

            //ProjectInstance projectInstance = new ProjectInstance(msbuildFileName);
            //var result = manager.Build(new BuildParameters()
            //{
            //    DetailedSummary = true,
            //},
            //         new BuildRequestData(projectInstance, new string[] { "Build" }));
            //var buildResult = result.ResultsByTarget["Build"];
            //var buildResultItems = buildResult.Items;

            //return;

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Configure();

            using (ProcessIcon.Start())
            using (Client.Start(p2pAddress, p2pPort))
            using (WebServer.Start())
            {
                WebServer.OnDragging += WebServer_OnDragging;

                fmDrag.SetDrag(false);

                #region posts

                //Client.Post("[Extension]", Utils.ToAddressSizeBase64String("Extension"));

                //Client.Post("Name", Utils.ToAddressSizeBase64String("Name"));

                //Client.Post("Title", Utils.ToAddressSizeBase64String("Title"));

                //Client.Post("Artist", Utils.ToAddressSizeBase64String("Artist"));



                //Client.Post("Comment", Utils.ToAddressSizeBase64String("Comment"));

                //Client.Post("Genre", Utils.ToAddressSizeBase64String("Genre"));


                //Client.Post("Track", Utils.ToAddressSizeBase64String("Track"));

                //Client.Post("Lyrics", Utils.ToAddressSizeBase64String("Lyrics"));

                //Client.Post("Grouping", Utils.ToAddressSizeBase64String("Grouping"));

                //Client.Post("BeatsPerMinute", Utils.ToAddressSizeBase64String("BeatsPerMinute"));

                //Client.Post("Disc", Utils.ToAddressSizeBase64String("Disc"));
                //Client.Post("Duration", Utils.ToAddressSizeBase64String("Duration"));
                //Client.Post("Description", Utils.ToAddressSizeBase64String("Description"));
                //Client.Post("AudioBitrate", Utils.ToAddressSizeBase64String("AudioBitrate"));
                //Client.Post("AudioSampleRate", Utils.ToAddressSizeBase64String("AudioSampleRate"));

                //Client.Post("BitsPerSample", Utils.ToAddressSizeBase64String("BitsPerSample"));
                //Client.Post("AudioChannels", Utils.ToAddressSizeBase64String("AudioChannels"));
                //Client.Post("Quality", Utils.ToAddressSizeBase64String("Quality"));


                //Client.Post("Album", Utils.ToAddressSizeBase64String("Album"));

                //Client.Post("MIME Type", Utils.ToAddressSizeBase64String("MIME Type"));

                //Client.Post("Height", Utils.ToAddressSizeBase64String("Height"));

                //Client.Post("Width", Utils.ToAddressSizeBase64String("Width"));

                //Client.Post("Year", Utils.ToAddressSizeBase64String("Year"));

                #endregion

                UIHelper = new UIHelper();

                UIHelper.Show();

                UIHelper.Visible = false;

                Application.Run();
            }
        }

        static void Configure()
        {
            webCache = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, webCache);

            if (!Directory.Exists(webCache))
                Directory.CreateDirectory(webCache);

            #region app.config

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings["p2pPort"] == null ||
                string.IsNullOrWhiteSpace(config.AppSettings.Settings["p2pPort"].Value))
            {
                p2pPort = Utils.GetAvaiablePort();
                config.AppSettings.Settings.Add("p2pPort", p2pPort.ToString());
            }
            else
                p2pPort = Convert.ToInt32(config.AppSettings.Settings["p2pPort"].Value);

            if (config.AppSettings.Settings["p2pAddress"] == null ||
                string.IsNullOrWhiteSpace(config.AppSettings.Settings["p2pAddress"].Value))
            {
                p2pAddress = Utils.GetAddress();
                config.AppSettings.Settings.Add("p2pAddress", Utils.ToBase64String(p2pAddress));
            }
            else
            {
                p2pAddress = Utils.FromBase64String(config.AppSettings.Settings["p2pAddress"].Value);
            }

            if (config.AppSettings.Settings["webPort"] == null ||
                string.IsNullOrWhiteSpace(config.AppSettings.Settings["webPort"].Value))
            {
                WebPort = Utils.GetAvaiablePort();
                config.AppSettings.Settings.Add("webPort", WebPort.ToString());
            }
            else
            {
                WebPort = int.Parse(config.AppSettings.Settings["webPort"].Value);
            }

            config.Save(ConfigurationSaveMode.Modified);

            #endregion
        }

        static void WebServer_OnDragging(bool dragging, string dragId, string userAddress)
        {
            fmDrag.SetDrag(dragging, dragId, userAddress);
        }
        
        static bool Install()
        {
            var programFiles = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                    AppName + "\\");
            
            var target = Path.Combine(programFiles, AppName + ".exe");

            if(AppDomain.CurrentDomain.BaseDirectory != programFiles)
            {
                Directory.CreateDirectory(programFiles);

                File.Copy(AppDomain.CurrentDomain.FriendlyName, target, true);

                ProcessStartInfo p = new ProcessStartInfo(target);

                //p.WorkingDirectory = programFiles;

                System.Diagnostics.Process.Start(p);

                return true;
            }

            return false;
        }
    }
}
